import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/delete_blog")
public class BlogDeleteServlet extends HttpServlet {
    //删除博客
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.约定请求和响应格式
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html; charset=utf8");
        //2.通过会话获取当前用户ID
        HttpSession session = req.getSession();
        if(session == null) {
            resp.setStatus(403);
            resp.getWriter().write("当前未登录，不可以删除博客!");
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            resp.getWriter().write("当前未登录，不可以删除博客!");
            return;
        }
        int userId = user.getUserId();
        //3.从query string中获取当前博客ID
        String blogId = req.getParameter("blogId");
        if(blogId == null) {
            resp.setStatus(403);
            resp.getWriter().write("当前博客ID不存在!");
            return;
        }
        //4.从数据库中通过该博客ID获取作者ID，对比当前用户ID是否一致
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
        if(blog.getUserId() != userId) {
            resp.setStatus(403);
            resp.getWriter().write("这不是您的博客,不可以删除!");
            return;
        }
        //5.删除博客
        blogDao.delete(Integer.parseInt(blogId));
        //6.重定向到博客列表
        resp.sendRedirect("blog_list.html");
    }
}
